#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"

typedef struct _SdkMessage
{
	UINT32		msgId;
	void*		data;
	UINT32		length;
}SdkMessage, *PSdkMessage;

static OSMsgQRef    sdkTaskMsgQ;

#define SDK_TASK_MSGQ_MSG_SIZE              (sizeof(SdkMessage))
#define SDK_TASK_MSGQ_QUEUE_SIZE            (200)

#define SDK_TASK_1_THREAD_PRIO                110
#define SDK_TASK_2_THREAD_PRIO                111

#define _STACK_1_SIZE			0x2000
#define _STACK_2_SIZE			0x2000
static void* _task_1_stack = NULL;
static void* _task_2_stack = NULL;

static OSTaskRef _task_1_ref = NULL;
static OSTaskRef _task_2_ref = NULL;


int sdk_task_send_msgq(SdkMessage * msg)
{
	int ret = 0;
	OSA_STATUS status = OSAMsgQSend(sdkTaskMsgQ, SDK_TASK_MSGQ_MSG_SIZE, (void*)msg, OSA_NO_SUSPEND);
	if (status != OS_SUCCESS) {
		LOG_PRINTF("%s, OSAMsgQSend lose, msg->id=%d, status=%d", __FUNCTION__, msg->msgId, status);
        if (msg->data) {
            free(msg->data);
        }
		ret = -1;
	}	
	
	return ret;
}

static char* sdk_strdup(const char* str)
{
	char* dst;

	dst = (char*) malloc (strlen(str) + 1);
	if (dst != NULL)
	{
		strcpy(dst, str);
	}

	return dst;
}

static void _task_1(void *ptr)
{
	OS_STATUS  status;
	SdkMessage sdkMsg = {0};

    while(1) {
		status = OSAMsgQRecv(sdkTaskMsgQ, (void *)&sdkMsg, SDK_TASK_MSGQ_MSG_SIZE, OSA_SUSPEND);
		
		if (status == OS_SUCCESS){
			LOG_PRINTF("%s: sdkMsg msgId: %d\n", __FUNCTION__, sdkMsg.msgId);
			LOG_PRINTF("%s: sdkMsg data: %s\n", __FUNCTION__, sdkMsg.data);
			LOG_PRINTF("%s: sdkMsg length: %d\n", __FUNCTION__, sdkMsg.length);
		}
		
		if (sdkMsg.data)
			free(sdkMsg.data);
    }
}

static void _task_2(void *ptr)
{
	SdkMessage sdkMsg = {0};	
	PSdkMessage pSdkMsg = &sdkMsg;
	
	int msgID = 0;
	
    while(1){
		
		sleep(5);
		
		memset(pSdkMsg, 0x00, sizeof(SdkMessage));
		
		pSdkMsg->msgId = msgID;		
		pSdkMsg->data = (char *)sdk_strdup("This is a test message!");
		pSdkMsg->length = strlen("This is a test message!");
				
		LOG_PRINTF("%s: send msgID: %d \n", __FUNCTION__, msgID);
		sdk_task_send_msgq(pSdkMsg);
		
		msgID++;
    }
}

int main(void)
{	
	OS_STATUS  status;
	
	_task_1_stack = malloc(_STACK_1_SIZE);
    ASSERT(_task_1_stack != NULL);
	_task_2_stack = malloc(_STACK_2_SIZE);
    ASSERT(_task_2_stack != NULL);

    /*creat message*/
    status = OSAMsgQCreate(&sdkTaskMsgQ, "sdkTaskMsgQ", SDK_TASK_MSGQ_MSG_SIZE, SDK_TASK_MSGQ_QUEUE_SIZE, OS_FIFO);
    ASSERT(status == OS_SUCCESS);

    status = OSATaskCreate(&_task_1_ref, _task_1_stack, _STACK_1_SIZE, SDK_TASK_1_THREAD_PRIO, "_task_1", _task_1, NULL);
    ASSERT(status == OS_SUCCESS);
	
    status = OSATaskCreate(&_task_2_ref, _task_2_stack, _STACK_1_SIZE, SDK_TASK_2_THREAD_PRIO, "_task_2", _task_2, NULL);
    ASSERT(status == OS_SUCCESS);

	return 0;
}